package com.gitee.feizns.permission.menu.spring.boot.starter;

import com.gitee.feizns.premission.menu.intercetor.MenuEnumVerificationInterceptor;
import com.gitee.feizns.premission.menu.intercetor.VerificationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author feizns
 * @since 2019/5/10
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(PermissionMenuProperties.class)
public class PermissionMenuAutoConfiguration implements WebMvcConfigurer {

    @Autowired
    private PermissionMenuProperties properties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(menuHandlerInterceptor());
    }

    private HandlerInterceptor menuHandlerInterceptor() {
        try {
            VerificationHandler handler = menu -> false;

            if ( properties.getHandlerClass() != null )
                handler = properties.getHandlerClass().newInstance();

            MenuEnumVerificationInterceptor<?> interceptor
                    = new MenuEnumVerificationInterceptor<>(properties.getAnnotation(), handler);
            return interceptor;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

}
